import 'dart:io';
import 'dart:math';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';

/// 描述: 加载图片可以设置圆角
/// 
/// @Author tangzhentao
///  @CreatedTime 14:04 2022/6/18
///

class OvalImage extends StatelessWidget {
  /// 图片地址
  final String? url;
  /// 图片圆角
  final BorderRadius? radius;
  /// 图片大小
  final Size size;
  /// 图片填充方式
  final BoxFit fit;
  /// 描边
  final BorderSide? side;
  /// 网络图片，加载错误情况下展示错误widget还是默认图
  final bool showError;
  /// 网络图片，重试点击
  final GestureTapCallback? onTap;
  /// 默认展示图
  final String? placeholder;
  /// 网络图片，loading效果是否展示[placeholder]
  final bool loadIsDefault;
  /// 默认展示图背景色
  final Color bgColor;
  /// 网络图片，加载错误情况下是否展示错误Widget
  final Color? blendModelColor;

  const OvalImage(this.url,{
    super.key,
    this.radius,
    required this.size,
    this.fit = BoxFit.cover,
    this.side,
    this.onTap,
    this.showError = false,
    this.placeholder,
    this.loadIsDefault = false,
    this.bgColor = XfgColor.colorE8,
    this.blendModelColor,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: SizedBox(
        width: size.width,
        height: size.height,
        child: LayoutBuilder(
            builder: (ctx, constraint) {
              final realSize = Size(constraint.maxWidth, constraint.maxHeight);
              return ClipRRect(
                borderRadius: radius ?? BorderRadius.zero,
                child: Container(
                  decoration: side != null ? BoxDecoration(border: Border.fromBorderSide(side!)): null,
                  child: _buildChildWidget(realSize),
                ),
              );
            }
        ),
      )
    );
  }

  Widget _buildChildWidget(Size realSize) {
    if (url?.startsWith("http") == true) {
      return ExtendedImage.network(
        url!,
        fit: fit,
        width: realSize.width,
        height: realSize.height,
        loadStateChanged: (state) {
          switch(state.extendedImageLoadState) {
            case LoadState.loading:
              return loadIsDefault ? _buildDefaultImageWidget(realSize) : Container(
                color: XfgColor.background,
                alignment: Alignment.center,
                child: CircularProgressIndicator(color:  HSVColor.fromAHSV(1, url.hashCode % 360.0, 0.1, 1).toColor(), strokeWidth: XfgSize().size2),
              );
            case LoadState.completed:
              return ExtendedRawImage(
                image: state.extendedImageInfo?.image,
                width: realSize.width, height: realSize.height,
                fit: fit,
                color: blendModelColor,
              );
            case LoadState.failed:
              return showError ? Container(
                alignment: Alignment.center,
                color: XfgColor.background,
                child: Icon(Icons.error_outlined, size: min(realSize.width, realSize.height) * 0.8, color: Colors.red),
              ) : _buildDefaultImageWidget(realSize);
          }
        },
      );
    } else if (url?.startsWith("assets/") == true) {
      return ExtendedImage.asset(url!, width: realSize.width, height: realSize.height, fit: fit,);
    } else if (url?.startsWith("file") == true || (url?.startsWith("/") == true && url?.startsWith('//') == false)) {
      return ExtendedImage.file(File(url!), width: realSize.width, height: realSize.height, fit: fit,);
    } else {
      return _buildDefaultImageWidget(realSize);
    }
  }

  /// 构建默认图片
  Widget _buildDefaultImageWidget(Size realSize) {
    if (placeholder == null) {
      final minSize = min(realSize.width, realSize.height);
      final width = minSize * 0.5;
      final height = width / 1.2;
      return Container(
        width: realSize.width,
        height: realSize.height,
        alignment: Alignment.center,
        color: bgColor,
        child: Image.asset(Res.imagesPlaceholder, width: width, height: height),
      );
    } else {
      return ExtendedImage.asset(placeholder!, width: realSize.width, height: realSize.height, fit: fit);
    }
  }
}
